package com.yuntsg.nnsfcp.controller.front;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuntsg.nnsfcp.common.beans.ResultBean;
import com.yuntsg.nnsfcp.common.exceptions.Unlogin2Exception;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.common.utils.StringUtil;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.nnsfcp.front.entity.UserInfo;
import com.yuntsg.nnsfcp.front.mapper.UserInfoMapper;
import com.yuntsg.nnsfcp.service.front.impl.SessionListener;
import com.yuntsg.nnsfcp.service.front.ut.BCryptPasswordEncoder;
import com.yuntsg.nnsfcp.service.front.ut.ImageUtil;
import com.yuntsg.nnsfcp.service.front.ut.TokenUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

/**
 * @Author: 葛成瑞
 * @Date: 2024/9/25 10:03
 */

@Slf4j
@RestController
@RequestMapping("front_login")
//@Api(description = "(前台)用户登录")
public class LoginController {
    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    TokenUtils tokenUtils;

    @Resource
    UserUtil userUtil;


    @GetMapping("/check-login")
//    @ApiOperation(value = "检测用户登录")
    public ResultBean<Object> checkLogin(HttpServletRequest request) {
        Integer frontUid = userUtil.getCheckFrontUid();
        log.info("check_+++" + frontUid);
        if (StringUtil.isNull(frontUid)) {
            throw new Unlogin2Exception();
        }
        return new ResultBean("");

    }

    /**
     * 用户登陆验证
     *
     * @param serverUserInfo 用户信息
     * @return
     */
//    @ApiOperation(value = "用户登陆", notes = "用户登陆验证, 参数将用户实体转换为 Json格式 \n {\"password\":\"123456\",\"account\":\"lisi\"}")
    @PostMapping("login")
    public ResultBean<Object> userLogin(HttpServletRequest request, @RequestBody UserInfo serverUserInfo) {
        CheckUtil.check(serverUserInfo != null, "登陆信息为空");
//        CheckUtil.check(false, "系统迁移维护,大约2024年1月15日开放");
//        StringBuffer requestURL = request.getRequestURL();

        String account = serverUserInfo.getAccount();
        if (!StringUtils.isEmpty(account)) {
            String password = serverUserInfo.getPassword();
            UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", account));
            if (userInfo == null) {
                log.info("============用户名不存在1=========");
                log.info("account: " + account);
                log.info("password: " + password);
                CheckUtil.check(false, "用户名不存在");
            } else {
                boolean matches = new BCryptPasswordEncoder().matches(password, userInfo.getPassword());
                if (matches) {
                    if (userInfo.getIsDelete() == 1) {
                        CheckUtil.check(false, "用户名已被删除");
                    }
                    if (userInfo.getIsBack() == 1) {
                        CheckUtil.check(false, "用户名已被加入黑名单");
                    }

                    String serverToken = request.getHeader("token");
                    String userInfoToken = userInfo.getToken();
                    log.info("servertoken+" + serverToken);
                    log.info("userInfoToken+" + userInfoToken);
                    //TODO 校验重复登陆
                    //boolean isLogin = SessionListener.isAlreadyEnter(request.getSession(), userInfo.getName());
                    boolean isLogin = true;
                    if (!isLogin || StringUtils.isEmpty(serverToken) || StringUtils.isEmpty(userInfoToken)) {
                        log.info("登陆成功: " + userInfo.getName());
//                        final String userId = String.valueOf(userInfo.getId());
//                        String token = TokenUtil2.createToken(userId);
                        String token = tokenUtils.createToken(userInfo.getId() + "", userInfo.getName(), userInfo.getPhone(), userInfo.getAccount());
                        if (!StringUtils.isEmpty(token)) {
                            log.info("写入token");
                            //token存入redis
                            //redisTemplate.opsForValue().set(token, userId, System.currentTimeMillis() + 20 * 60 * 1000, TimeUnit.MILLISECONDS);
                            //登陆成功响应回的数据
                            HashMap<String, Object> returnMap = new HashMap<>(16);
                            returnMap.put("name", userInfo.getName());
                            returnMap.put("account", userInfo.getAccount());
                            returnMap.put("uid", String.valueOf(userInfo.getId()));
                            returnMap.put("token", token);
                            //判断用户是否第一次登陆
                            String authorEn = userInfo.getAuthorEn();
                            String name = userInfo.getName();
                            String email = userInfo.getEmail();
                            if (
//                                    StringUtils.isNotEmpty(authorAddressCn)
                                    StringUtils.isNotEmpty(name)
                                            && StringUtils.isNotEmpty(email)
                                            && StringUtils.isNotEmpty(authorEn)
//                                    && StringUtils.isNotEmpty(authorAddressEn)
                            ) {

                                returnMap.put("first", false);
                            } else {
                                returnMap.put("first", true);
                            }
                            //本地存储一份 token, 用于比对
                            userInfo.setToken(token);
                            userInfoMapper.updateById(userInfo);
                            HttpSession session = request.getSession();
                            //存sesion一份
                            SessionListener.setSessionByUserInfo(session, userInfo);
                            //添加用户登陆在线状态
                            SessionListener.addUserLogin(session);
                            session.setMaxInactiveInterval(2000);

                            return new ResultBean<>(JSON.toJSONString(returnMap));
                        } else {
                            CheckUtil.check(false, "登陆失败");

//                            return new ResultBean<>("登陆失败");
                        }
                    } else {
                        log.info("用户已登陆");
                        CheckUtil.check(false, "该用户已登录");
//                        return new ResultBean<>("该用户已登录");
                    }
                } else {
                    log.info("account: " + account);
                    log.info("password: " + password);
                    CheckUtil.check(false, "密码错误");
//                    return new ResultBean<>("密码错误");
                }
            }
        }
        CheckUtil.check(false, "账号不能为空");
        return new ResultBean<>();
//        return new ResultBean<>("账号不能为空");
    }


    /**
     * 获取图片验证码
     *
     * @param request  请求
     * @param response 响应
     */
    @GetMapping("/createImage")
//    @ApiOperation(value = "获取图片验证码", notes = "获取图片验证码")
    public ResultBean<Object> createImage(HttpServletRequest request, HttpServletResponse response) {
        //先清空
        if (request.getSession().getAttribute("imgCode") != null) {
            request.getSession().removeAttribute("imgCode");
        }

        //判断是不是在自己的对应页面中访问资源.
        String referer = request.getHeader("Referer");
        CheckUtil.check(StringUtils.isNotEmpty(referer), "非法访问");

//        if (referer.contains("login") || referer.contains("info") || referer.contains("register")) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        ImageUtil c = new ImageUtil(request, response);
        try {
            BufferedImage image = c.createImage("imgCode");
            OutputStream b = response.getOutputStream();
            ImageIO.write(image, "JPEG", b);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        }
//        else {
//            CheckUtil.check(false, "非法访问");
//        }
        return new ResultBean<>(1);
    }

    /**
     * token的超时处理
     *
     * @return
     */
//    @GetMapping("token_time_out")
//    @ApiOperation(value = "token的超时处理", notes = "token的超时处理")
//    public ResultBean<Object> tokenTimeOutHandle(String serverToken) {
//        Object userIdObj = redisTemplate.opsForValue().get(serverToken);
//        SmallTool.printMess(serverToken);
//        SmallTool.printMess(userIdObj);
//        String token = "";
//        if (userIdObj != null) {
//            String userId = userIdObj.toString();
//            UserInfo userInfo = userInfoMapper.selectById(userId);
//            if (userInfo != null) {
//                token = TokenUtil.createToken(userId);
//                redisTemplate.delete(serverToken);
//                redisTemplate.opsForValue().set(token, userId, System.currentTimeMillis() + 40 * 60 * 1000, TimeUnit.MILLISECONDS);
//                //登陆成功响应回的数据
//                HashMap<String, String> returnMap = new HashMap<>(16);
//                returnMap.put("name", userInfo.getName());
//                returnMap.put("account", userInfo.getAccount());
//                returnMap.put("uid", String.valueOf(userInfo.getId()));
//                returnMap.put("token", token);
//                return new ResultBean<>(returnMap);
//            }
//        }
//        return new ResultBean<>(-1);
//    }


    /**
     * 校验图片验证码
     *
     * @param request 请求
     * @param imgCode 用户输入的图片验证码
     * @return
     */
    @GetMapping("/checkImage")
//    @ApiOperation(value = "校验图片验证码", notes = "校验图片验证码")
    public ResultBean<Object> checkImage(HttpServletRequest request, String imgCode) {
        CheckUtil.check(StringUtils.isNotEmpty(imgCode), "请输入图片中的验证码");
        //获取图片验证码
        Object codeObj = request.getSession().getAttribute("imgCode");
        if (codeObj != null) {
            //不区分大小写
            String code = codeObj + "";
            code = code.toLowerCase().replaceAll(" ", "");
            imgCode = imgCode.replaceAll(" ", "").toLowerCase();

            if (imgCode.equals(code)) {
                return new ResultBean<>(true);
            }
        }
        return new ResultBean<>(false);
    }

    /**
     * 退出登陆
     * 2021年2月18日17:19:08 目前不知道这块是什么原因  用了两套token机制吗?
     *
     * @return
     */
    @GetMapping("/logout")
//    @ApiOperation(value = "退出登陆", notes = "退出登陆")
    public ResultBean<Object> logout(HttpServletRequest request) {
//        String token = request.getHeader("token");
//        DecodedJWT jwt = TokenUtil2.deToken(token);
        try {
            request.getSession().invalidate();
        } catch (Exception e) {

        }


        return new ResultBean<>(1);
//        if (jwt != null) {
//            //成功解析token的处理
//            SessionListener.removeLogin(request.getSession(), userInfoMapper);
//            String issuer = jwt.getIssuer();
//            if ("ljx".equals(issuer)) {
//                String userId = jwt.getClaim("userId").asString();
//                UserInfo userInfo = userInfoMapper.selectById(userId);
//                if (userInfo != null) {
//                    log.info("退出账户: " + userInfo.getName());
//                    userInfo.setToken("");
//                    userInfo.setLastTime(LocalDateTime.now());
//                    userInfoMapper.updateById(userInfo);
//                    //redisTemplate.delete(token);
//                    return new ResultBean<>(1);
//                }
//            }
//        } else {
//            //获取请求头的userId处理
//            String userId = request.getHeader("UID");
//            UserInfo userInfo = userInfoMapper.selectById(userId);
//            if (userInfo != null) {
//                log.info("退出账户: " + userInfo.getName());
//                userInfo.setToken("");
//                userInfo.setLastTime(LocalDateTime.now());
//                userInfoMapper.updateById(userInfo);
//                request.getSession().removeAttribute("time");
//                redisTemplate.delete(token);
//                return new ResultBean<>(1);
//            }
//        }
//        return new ResultBean<>(0);
    }


}
